package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.UploadProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
//使用配置类
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    private final Logger log = LoggerFactory.getLogger(UploadService.class);

    ////允许类型放配置文件
    //private static  final List<String> ALLOW_TYPE = Arrays.asList("image/jpeg","image/png","image/bmp");
      //注入配置类
        @Autowired
        private UploadProperties uploadProperties;

    public String uploadImage(MultipartFile file) {

        try {
            //校验文件类型
            String contentType = file.getContentType();
            if(!uploadProperties.getAllowTypes().contains(contentType)){
                throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
            }

            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image==null){
                throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
            }

            ////保存文件
            //File dest = new File("D:\\JAVA全套资料\\资料\\FastDFS", file.getOriginalFilename());//保存的路径
            //file.transferTo(dest);

            //上传到fastdfs
            //获取后缀
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(),".");
            //上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            //返回路径
            //这里路径可以放在配置文件里
            return uploadProperties.getBaseUrl() + storePath.getFullPath();
        }catch (IOException e){
            log.error("上传文件失败",e);
            throw  new LyException(ExceptionEnums.UPLOAD_FILE_ERROR);
        }
    }
}
